package org.example.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WebSocketServer {
    public static void main(String[] args) {
        ServerBootstrap bootstrap = new ServerBootstrap();

        // Acceptor线程
        EventLoopGroup acceptor = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();

        bootstrap.group(acceptor, worker);

        bootstrap.localAddress(8085);

        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        // ByteBuf分配器
        bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        // 连接超时时间3秒
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);

        // 服务端channel
        bootstrap.channel(NioServerSocketChannel.class);

        // worker处理器
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // websocket协议，是http协议升级上来的，需要添加http协议处理器
                ch.pipeline().addLast(new HttpRequestDecoder());
                ch.pipeline().addLast(new HttpResponseEncoder());
                // 可以将DefaultHttpRequest转换成FullHttpRequest
                ch.pipeline().addLast(new HttpObjectAggregator(65535));
                ch.pipeline().addLast(new WebSocketServerProtocolHandler("/websocket",null,true,10*1024));
                // 增加网页的逻辑处理
                // 自定义websocket业务处理器
                ch.pipeline().addLast(new TextWebSocketFrameHandler());
            }
        });

        try {
            ChannelFuture future = bootstrap.bind().sync();
            Channel channel = future.channel();
            channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    log.info("连接已经关闭");
                }
            }).sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅关闭线程组
            acceptor.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
